import React, {Component} from 'react'
import {connect} from 'react-redux'
import F from 'lodash/fp'
import {contentChange, savedPages} from '../actions/content-change'

function mark(className) {
    var selected = getSelection()
    if (selected.anchorNode !== selected.focusNode) {
        return alert('请勿夸区域选择')
    }
    var range = selected.getRangeAt(0)
    const node = range.startContainer

    if (node.nodeName == '#text') {
        var elm = $(node).parent()
    } else {
        var elm = $(node)
    }

    let html = ''

    Array.from(elm[0].childNodes).forEach(n => {
        if (n === node) {
            const txt = $(n).text()
            html += txt.slice(0, range.startOffset) +
                `<span class="${className}">` +
                txt.slice(range.startOffset, range.endOffset) +
                '</span>' +
                txt.slice(range.endOffset)
        } else {
            html += n.nodeName === '#text' ? $(n).text() : n.outerHTML
        }
    })
    let $elm = elm.html(html).parents('.elm')
    return [$elm.data('path').toString().split('.'), $elm.html()]
}

class TopButtons extends Component {
    render() {
        let {mark} = this.props
        return (
            <div>
                <div>
                    <button
                        className="edit-box-btn edit-save edit-preview"
                        id="preview-button"
                        data-am-modal="{target: '#modal-preview', closeViaDimmer: 1, width: 800, height: 600}"
                        onClick={() => {
                            window.slider = Card.render(F.map('elements', this.props.card.pages), $('.invit-box').html('').get(0))
                        }}
                    >
                        预览
                    </button>
                    <button className="edit-box-btn edit-preview edit-save" onClick={window.save}>保存</button>
                    <button className="edit-box-btn edit-quit" onClick={window.exit}>退出</button>
                </div>

                {this.props.mode === 'template' ? <div style={{marginTop: '20px'}}>
                    <button className="edit-box-mark" onClick={() => mark('mark-xl')}>新郎名字</button>
                    <button className="edit-box-mark" onClick={() => mark('mark-xn')}>新娘名字</button>
                    <button className="edit-box-mark" onClick={() => mark('mark-address')}>地址</button>
                </div> : null}
            </div>
        )
    }
}

module.exports = connect(
    state => state
    , (dispatch, props) => ({
        mark: className => {
            let [path, content] = mark(className)
            dispatch(contentChange(content, path, 'Card'))
        }
    })
)(TopButtons)